package lk.mrt.cse.wihidum.receiver;

import lk.mrt.cse.wihidum.processor.*;
import lk.mrt.cse.wihidum.util.*;
import org.apache.axiom.om.OMException;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.receivers.AbstractMessageReceiver;
import org.apache.log4j.Logger;

import java.util.HashMap;

public class InOnlyMessageReceiver extends AbstractMessageReceiver {
    private static final Logger logger = Logger.getLogger(InOnlyMessageReceiver.class);
    private Processor publicationProcessor;
    private Processor subscriptionProcessor;
    HashMap<String, String> brokerMap;
    long i = 0;

    public InOnlyMessageReceiver() {
        publicationProcessor = new PublicationProcessor();
        subscriptionProcessor = new SubscriptionProcessor();
        brokerMap = SelfReader.read();
    }

    protected void invokeBusinessLogic(MessageContext inMessageContext) throws AxisFault {
        try {
            SOAPEnvelope inSoapEnvelope = inMessageContext.getEnvelope();
            String action = inMessageContext.getOptions().getAction();

            if (action.equals(WihidumConstants.Operations.PUBLISH)) {
                i++;
                String uuid = brokerMap.get("id").concat("_" + i);// UUID.randomUUID().toString().concat("_"+brokerMap.get("id"));
                logger.info("An event received with ID#" + uuid);
                // Hand over the message to the publication processor
                publicationProcessor.processMessage(inSoapEnvelope, uuid);
            }
        }
        catch (NullPointerException ex) {
            logger.error("Error in recognizing received message format", ex);
        }
        catch (OMException ex) {
            logger.error("Error in recognizing received message format", ex);
        }
    }
}
